package com.ndood.authenticate.core.social.mini.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.social.UserIdSource;
import org.springframework.social.config.annotation.ConnectionFactoryConfigurer;
import org.springframework.social.config.annotation.SocialConfigurerAdapter;
import org.springframework.social.connect.ConnectionFactory;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.security.AuthenticationNameUserIdSource;

import com.ndood.authenticate.core.properties.MiniProgramProperties;
import com.ndood.authenticate.core.properties.SecurityProperties;
import com.ndood.authenticate.core.social.SocialConfig;
import com.ndood.authenticate.core.social.mini.connect.MiniOauth2ConnectionFactory;

/**
 * 微信小程序登录配置
 */
@Configuration
@ConditionalOnProperty(prefix = "ndood.security.social.mini", name = "app_id")
public class MiniAutoConfiguration extends SocialConfigurerAdapter {

	@Autowired
	private SecurityProperties securityProperties;

	@Autowired
	private SocialConfig socialConfig;

	@Override
	public void addConnectionFactories(ConnectionFactoryConfigurer configurer, Environment environment) {
		configurer.addConnectionFactory(createConnectionFactory());
	}

	protected ConnectionFactory<?> createConnectionFactory() {
		MiniProgramProperties miniConfig = securityProperties.getSocial().getMini();
		return new MiniOauth2ConnectionFactory(miniConfig.getProvider_id(), miniConfig.getApp_id(),
				miniConfig.getApp_secret());
	}

	@Override
	public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
		return socialConfig.getUsersConnectionRepository(connectionFactoryLocator);
	}

	/**
	 * https://www.programcreek.com/java-api-examples/index.php?api=org.springframework.social.UserIdSource
	 */
	@Override
	public UserIdSource getUserIdSource() {
		return new AuthenticationNameUserIdSource();
	}
	
}